<template>
  <div>
    <div class="app-container" v-show="showIndex === 0">
      <div class="header-search">
        <div class="header-search-title">查找茶种：</div>
        <div class="item">
          <el-select
            class="search-select"
            size="mini"
            v-model="searchLabel"
            @change="changeSelect"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            class="search-input"
            v-model="search"
            size="mini"
            :placeholder="'搜索' + selectInput"
          />
          <el-button
            @click="searchValue"
            class="search-button"
            size="mini"
            type="primary"
            >搜索
          </el-button>
        </div>
        <div class="item-other">
          <el-button
            @click="addLine"
            class="search-button"
            size="mini"
            type="success"
            >添加茶种
          </el-button>
        </div>
        <div class="item-other">
          <el-button
            @click="batchDownload"
            class="search-button"
            size="mini"
            type="success"
            >批量下载（{{ selectNum }}）
          </el-button>
        </div>
        <div class="item-other">
          <el-button
            @click="deleteMore"
            class="search-button"
            size="mini"
            type="danger"
            >批量删除（{{ selectNum }}）
          </el-button>
        </div>
        <div class="item-other">
          <el-button
            @click="downloadAll"
            class="search-button"
            size="mini"
            type="success"
            >全部下载
          </el-button>
        </div>
        <div class="item-other">
          <el-button
            @click="reflesh"
            class="search-button"
            size="mini"
            type="success"
            >刷新
          </el-button>
        </div>
      </div>
      <div v-loading="loading" style="min-height: 620px">
        <el-table
          v-show="!loading"
          ref="TeaList"
          :data="tableData"
          height="620"
          style="width: 100%; height: 518px"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column label="编号" prop="id" width="150px" align="center">
          </el-table-column>
          <el-table-column label="中文名" prop="chineseName"> </el-table-column>
          <el-table-column label="拉丁名" prop="latinName"> </el-table-column>
          <el-table-column label="种植时间" prop="growYear"> </el-table-column>
          <el-table-column label="等级" prop="grade"> </el-table-column>

          <el-table-column label="来源省" prop="province"> </el-table-column>
          <el-table-column label="珍贵程度">
            <template slot-scope="scope">
              {{ scope.row["rareVariety"] === 0 ? "非贵品种" : "名贵品种" }}
            </template>
          </el-table-column>
          <el-table-column label="二维码图片" prop="path">
            <template slot-scope="scope">
              <div
                style="
                  display: flex;
                  justify-content: center;
                  width: 100px;
                  height: 100px;
                "
              >
                <!-- <img :src="url + scope.row['path']" /> -->
                <el-image
                  style=""
                  :src="url + scope.row['qrCodePath']"
                  :preview-src-list="[url + scope.row['qrCodePath']]"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column width="300" align="center" label="操作">
            <template slot-scope="scope">
              <div style="display: flex; justify-content: center">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleUpdate(scope.$index, scope.row)"
                >
                  修改
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="footer-pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="pageNum"
          :page-count="totalPages"
          @current-change="change"
          :pager-count="9"
        >
        </el-pagination>
      </div>
    </div>
    <add-view
      :showIndex.sync="showIndex"
      v-if="showIndex === 1"
      @goBack="goBack"
    />
    <update-view
      :updateId="updateId"
      :showIndex.sync="showIndex"
      v-if="showIndex === 2"
      @goBack="goBack"
    />

    <el-backtop :visibility-height="10"></el-backtop>
  </div>
</template>

<script>
import { list, deleteTea, downloadAll, batchDownload } from "@api/tea-manager";
import { Loading } from "element-ui";
import AddView from "./view/create.vue";
import UpdateView from "./view/update.vue";
import { mapState } from "vuex";
export default {
  components: {
    AddView,
    UpdateView,
  },
  name: "List",
  filters: {
    getRealTime(e) {
      console.log(e);
      if (e) {
        const time = new Date(e);
        const year = time.getFullYear();
        const _month = time.getMonth() + 1;
        const month = _month < 10 ? "0" + _month : _month;
        const day = time.getDay() < 10 ? "0" + time.getDay() : time.getDay();
        const hours =
          time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
        const min =
          time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
        const second =
          time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
        return (
          year +
          "-" +
          month +
          "-" +
          day +
          " " +
          hours +
          ":" +
          min +
          ":" +
          second
        );
      }
      return "";
    },
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 20,
      totalSize: 0,
      totalPages: 0,
      tableData: [],
      search: "",
      searchLabel: "",
      options: [
        {
          value: "",
          label: "请选择查询条件",
        },
        {
          value: "id",
          label: "编号",
        },
        {
          value: "grade",
          label: "等级",
        },
        {
          value: "chineseName",
          label: "中文名",
        },
        {
          value: "latinName",
          label: "拉丁名",
        },
      ],
      value: "",
      selectInput: "",
      select: [],
      showIndex: 0,
      loading: false,
      updateId: 0,
    };
  },
  created() {
    this.geList();
  },
  computed: {
    ...mapState({
      url: (state) => state.url,
    }),
    selectNum() {
      return this.select.length;
    },
  },
  methods: {
    downloadAll() {
      downloadAll({
        config: {
          responseType: "blob",
        },
      })
        .then((res) => {
          console.log(res);
          let link = document.createElement("a");
          link.href = window.URL.createObjectURL(new Blob([res.data]));
          link.target = "_blank";
          //文件名和格式
          link.download = "全部二维码.zip";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((err) => {
          this.$message.error("下载失败");
        });
    },
    batchDownload() {
      if (this.selectNum === 0) return this.$message.warning("您未需选择");
      const { select } = this;
      batchDownload({
        data: select,
        config: {
          responseType: "blob",
        },
      })
        .then((res) => {
          console.log(res);
          let link = document.createElement("a");
          link.href = window.URL.createObjectURL(new Blob([res.data]));
          link.target = "_blank";
          //文件名和格式
          link.download = "部分二维码.zip";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((err) => {
          this.$message.error("下载失败");
        });
    },
    goBack() {
      this.loading = true;
      this.geList(() => {
        setTimeout((res) => {
          this.loading = false;
        }, 1000);
      });
    },
    addLine() {
      this.showIndex = 1;
    },
    reflesh() {
      this.loading = true;
      this.geList(() => {
        setTimeout((res) => {
          this.loading = false;
        }, 1000);
      });
    },
    handleUpdate(index, row) {
      this.updateId = row["id"];
      this.showIndex = 2;
    },
    handleSelectionChange(e) {
      this.select = e.map((item) => item.id);
    },
    geList(callback) {
      list({
        page: this.pageNum - 1,
        size: this.pageSize,
        [this.searchLabel]: this.search,
      })
        .then((res) => {
          console.log(res);
          callback && callback();
          this.tableData = res.data.data["newFindList"];
          this.totalPages = res.data.data["totalPages"];
          console.log(this.totalPages);
        })
        .catch((err) => {
          callback && callback();
          console.log(err);
        });
    },
    changeSelect(e) {
      this.search = "";
      // console.log(e);
      // this.searchLabel = e;
      this.options.some((item, index) => {
        if (item.value === e) {
          this.selectInput = item.label;
          if (!item.value) {
            this.selectInput = "";
            this.geList();
          }
          return true;
        }
      });
    },
    searchValue() {
      if (!this.selectInput) return this.$message.info("请先选择类别");
      if (!this.search) return this.$message.info("请输入搜索内容");
      this.pageNum = 1;
      this.geList();
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
    deleteMore() {
      if (this.selectNum === 0) return this.$message.warning("您未需选择");
      this.$confirm("此操作将删除所选的茶种, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let loadingInstance = Loading.service({
            fullscreen: true,
          });
          deleteTea(this.select)
            .then((res) => {
              if (res.data.code === 200) {
                this.geList();
                loadingInstance.close();
                this.$message.success("删除成功");
                return;
              }
              this.geList();
              loadingInstance.close();
              this.$message.error(res.data.message);
            })
            .catch((err) => {
              console.log(err);
              loadingInstance.close();
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该茶种, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let loadingInstance = Loading.service({
            fullscreen: true,
          });
          deleteTea([row["id"]])
            .then((res) => {
              if (res.data.code === 200) {
                this.geList();
                loadingInstance.close();
                this.$message.success("删除成功");
                return;
              }
              this.geList();
              loadingInstance.close();
              this.$message.error(res.data.message);
            })
            .catch((err) => {
              console.log(err);
              loadingInstance.close();
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    change(e) {
      this.pageNum = e;
      this.geList();
    },
    getSomeQrCode() {},
  },
};
</script>


<style lang="scss" scoped>
.app-container {
  height: 730px;
  overflow: hidden;
  .header-search {
    display: flex;
    // width: 500px;
    > .header-search-title {
      width: 100px;
      color: #909399;
      font-size: 16px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    > .item {
      display: flex;
      overflow: hidden;
      width: 450px;
      justify-content: space-between;
      > .search-select {
        width: 250px;
        margin-right: 4px;
      }
      > .search-input {
        //width: 60px;
      }
      > .search-button {
        margin-left: 4px;
      }
    }

    > .item-other {
      margin-left: 20px;
    }
  }
  .footer-pagination {
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
